package com.teamone.etl.accountant.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.aliyuncs.exceptions.ClientException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.teamone.etl.accountant.dao.PersonalInformationDao;
import com.teamone.etl.accountant.dao.RechargeSheetDao;
import com.teamone.etl.accountant.entity.PersonalInformation;
import com.teamone.etl.accountant.entity.RechargeSheet;
import com.teamone.etl.accountant.service.RechargeSheetService;
import com.teamone.etl.config.AlipayConfig;
import com.teamone.etl.util.OrderUtils;
import com.teamone.etl.util.SendSmsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 充值明细表(RechargeSheet)表服务实现类
 *
 * @author makejava
 * @since 2021-01-20 15:38:56
 */
@Service("rechargeSheetService")
@Transactional(rollbackFor = Exception.class)
public class RechargeSheetServiceImpl implements RechargeSheetService {
    @Resource
    private RechargeSheetDao rechargeSheetDao;
    @Resource
    private PersonalInformationDao personalInformationDao;

    @Autowired
    private AlipayConfig alipayConfig;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public RechargeSheet queryById(Integer id) {
        return this.rechargeSheetDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    @Override
    public List<RechargeSheet> queryAllByLimit(int offset, int limit) {
        return this.rechargeSheetDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param rechargeSheet 实例对象
     * @return 实例对象
     */
    @Override
    public RechargeSheet insert(RechargeSheet rechargeSheet) {
        this.rechargeSheetDao.insert(rechargeSheet);
        return rechargeSheet;
    }

    /**
     * 修改数据
     *
     * @param rechargeSheet 实例对象
     * @return 实例对象
     */
    @Override
    public RechargeSheet update(RechargeSheet rechargeSheet) {
        this.rechargeSheetDao.update(rechargeSheet);
        return this.queryById(rechargeSheet.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.rechargeSheetDao.deleteById(id) > 0;
    }

    /**
     * 账户充值/添加充值记录
     * @param rechargeSheet
     * @return
     */
    @Override
    public int recharge(RechargeSheet rechargeSheet) {
        if(rechargeSheet.getAccountId()!=null && rechargeSheet.getTradingMoney()!=null){
            //获取用户编号
            Integer accountId = rechargeSheet.getAccountId();
            String rechargeId = OrderUtils.getOrderCode(accountId);
            rechargeSheet.setTradingName(AlipayConfig.PAYMENT);
            rechargeSheet.setRechargeId(rechargeId);
            rechargeSheet.setRechargeTime(new Date());
            rechargeSheet.setCreateTime(new Date());
            rechargeSheet.setUpdateTime(new Date());
            try {
                pay(rechargeId,AlipayConfig.PAYMENT,String.valueOf(rechargeSheet.getTradingMoney()),String.valueOf(accountId));
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
            int state = rechargeSheetDao.insert(rechargeSheet);
            //更新当前账户余额
            PersonalInformation personalInformation = personalInformationDao.queryById(rechargeSheet.getAccountId());
            personalInformation.setBalance(personalInformation.getBalance().add(rechargeSheet.getTradingMoney()));
            personalInformationDao.update(personalInformation);
            return state;
        }else {
            return 0;
        }
    }

    /**
     * 支付宝支付接口
     */
    public String pay(@RequestParam("rechargeId") String rechargeId,
                      @RequestParam("tradingName") String tradingName,
                      @RequestParam("tradingMoney") String tradingMoney,
                      @RequestParam("id") String id) throws AlipayApiException {
        /**
         * 1.封装RSA签名方式
         * gatewayUrl支付宝网关
         * app_id当前支付宝账户编号
         * merchant_private_key商户私钥
         * format格式化json
         * charset字符编码 utf-8
         * alipay_public_key支付宝公钥
         * sign_type支付宝签名方式 RSA2
         */
        AlipayClient alipayClient = new DefaultAlipayClient(
                AlipayConfig.gatewayUrl,
                alipayConfig.app_id,
                alipayConfig.merchant_private_key,
                AlipayConfig.format,
                AlipayConfig.charset,
                alipayConfig.alipay_public_key,
                AlipayConfig.sign_type);
        //2.创建Request请求
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        //3.封装对象   封装页面传递过来的参数
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setOutTradeNo(rechargeId);
        model.setSubject(tradingName);
        model.setTotalAmount(tradingMoney);
        model.setProductCode(id);
        request.setBizModel(model);
        //设置异步回调地址
        request.setNotifyUrl(AlipayConfig.notify_url);
        //设置同步回调地址
        request.setReturnUrl(AlipayConfig.return_url);
        //生成表单
        System.out.println("生成表单:"+alipayClient.pageExecute(request).getBody());
        return alipayClient.pageExecute(request).getBody();
    }

    /**
     * 充值明细表
     * @param accountId
     * @param rechargeTime
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageInfo<RechargeSheet> rechargeSheetList(Integer accountId,String rechargeTime, Integer page, Integer size) {
        PageHelper.startPage(page,size);
        List<RechargeSheet> rechargeSheetList = rechargeSheetDao.rechargeSheetList(accountId,rechargeTime);
        return new PageInfo<>(rechargeSheetList);
    }

    /**
     * 导入excel
     * @param accountId
     * @return
     */
    @Override
    public List<RechargeSheet> easyExcel(Integer accountId) {
        String fileName = "RechargeSheet.xlsx";
        EasyExcel.write(fileName,RechargeSheet.class).sheet("充值明细表").doWrite(rechargeSheetDao.easyExcel(accountId));
        return rechargeSheetDao.easyExcel(accountId);
    }

    @Override
    public List<RechargeSheet> findById(Integer accountId) {
        return rechargeSheetDao.findById(accountId);
    }

    /**
     * 定时器
     * @throws ClientException
     */
    @Scheduled(cron = "*/2 * * * * ?")
    public void timedTaskTesting() throws ClientException {
        /**
         * 定时器触发--------(30分钟触发一次)---------
         * 查询所有的账户
         */
        List<PersonalInformation> personalInformationList = personalInformationDao.findAll();
        for (PersonalInformation personalInformation : personalInformationList) {
            if (personalInformation.getBalance().compareTo(personalInformation.getWarningThreshold())==-1
            && personalInformation.getWarningStatus()==1){
                //当余额小于预警值时 并且 预警状态开启时可以发短信
                SendSmsUtil.sendSms(personalInformation.getWarningPhone());
            }
        }
    }
}